<template>
  <page-meta :root-font-size="$rootFontSize"></page-meta>
  <view>
    <u-loading-page
      :loading="isLoading"
      loading-mode="spinner"
      icon-size="56rpx"
      loading-text="拼命加载中..."
      fontSize="28rpx"
      class="z-50 top-0"
    ></u-loading-page>
    <view
      style="min-height: 100vh"
      class="bg-cover"
      :style="
        isRegister.styleVO.imagePath1
          ? `background:${isRegister.styleVO.styleInfo1}; background-image: url(${isRegister.styleVO.imagePath1})`
          : ``
      "
    >
      <!--注册-->
      <!-- #ifdef APP-PLUS -->
      <view
        class="fixed left-3 top-8 z-10 bg-white w-8 h-8 rounded-full flex justify-center shadow opacity-70"
        @click="onBack"
        ><u-icon name="arrow-left" color="#333333" size="36rpx"></u-icon
      ></view>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <view
        class="fixed left-3 top-3 z-10 bg-white w-8 h-8 rounded-full flex justify-center shadow opacity-70"
        @click="onBack"
        ><u-icon name="arrow-left" color="#333333" size="36rpx"></u-icon
      ></view>
      <!-- #endif -->
      <view v-if="isRegister.styleVO.imagePath2">
        <image
          class="w-full"
          mode="widthFix"
          :src="isRegister.styleVO.imagePath2"
        ></image>
      </view>
      <view class="mx-4 mt-3 mb-12">
        <view class="businessBox rounded-2xl pt-3 pb-6">
          <view class="mx-5">
            <view class="text-base text-center leading-10 mb-2.5">注册</view>
            <u--form :model="form" :rules="rules" ref="form" errorType="toast">
              <u-form-item
                class="px-5 rounded-full bg-inputGray-reg"
                prop="phone"
              >
                <u--input
                  v-model="form.phone"
                  type="number"
                  shape="circle"
                  border="none"
                  fontSize="32rpx"
                  color="#333333"
                  placeholderStyle="color: #333333"
                  placeholder="手机号"
                  clearable
                >
                </u--input>
              </u-form-item>
              <u-form-item
                class="px-5 rounded-full bg-inputGray-reg mt-4"
                prop="vcode"
              >
                <u-input
                  v-model="form.vcode"
                  type="number"
                  shape="circle"
                  border="none"
                  fontSize="32rpx"
                  color="#333333"
                  placeholderStyle="color: #333333"
                  placeholder="短信验证码"
                  clearable
                >
                  <template slot="suffix">
                    <u-code
                      ref="uCode"
                      @change="codeChange"
                      @end="codeEnd"
                      :seconds="seconds"
                      changeText="X秒重新获取"
                      class="text-light text-sm"
                    ></u-code>
                    <view @tap="getCode" :text="tips" class="text-sm">{{
                      tips
                    }}</view>
                  </template>
                </u-input>
              </u-form-item>
              <u-form-item
                class="px-5 rounded-full bg-inputGray-reg mt-4"
                prop="inviteCode"
              >
                <u--input
                  v-model="form.inviteCode"
                  shape="circle"
                  border="none"
                  fontSize="32rpx"
                  color="#333333"
                  placeholderStyle="color: #333333"
                  placeholder="邀请码"
                  :disabled="isDisabled"
                  disabledColor="none"
                  clearable
                >
                </u--input>
              </u-form-item>
            </u--form>
            <view class="flex justify-between items-center mt-7">
              <view class="text-sm" @click="goTo('login')"
                >已有账号？立即登录</view
              >
              <view @click="onRegister">
                <image
                  class="w-10 h-5 mr-4"
                  src="/static/images/business-go.png"
                ></image>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view>
        <image
          class="w-full"
          mode="widthFix"
          :src="isRegister.styleVO.imagePath3"
        ></image>
      </view>
      <view>
        <image
          class="w-full pb-3"
          mode="widthFix"
          :src="isRegister.styleVO.imagePath4"
        ></image>
      </view>
      <web-view :src="myUrl" @message="handleMessage" v-if="isWeb"></web-view>
    </view>
  </view>
</template>

<script>
import { register, getInviteStatus } from '../../services/user-details';
import { sendCode, sendVcodeLog } from '../../../services/user';

export default {
  data() {
    return {
      isLoading: true,
      //邀请码id
      id: undefined,
      isDisabled: true,
      //默认背景图路径
      imagePathDefault:
        process.env.VUE_APP_PATH != './'
          ? process.env.VUE_APP_PATH + '/static/images/business-bg.png'
          : '/static/images/business-bg.png',
      //webview页面携带参数天御行为验证码AppId
      myUrl:
        '/static/html/index.html?id=' +
        uni.getStorageSync('autoBuy' + uni.getStorageSync('autoBuy-platformId'))
          .captchaAppId
          ? uni.getStorageSync(
              'autoBuy' + uni.getStorageSync('autoBuy-platformId')
            ).captchaAppId
          : process.env.VUE_APP_SDK_APP_ID,
      //是否显示webview
      isWeb: false,
      isShow: false,
      tips: '',
      canGetCode: false,
      seconds: 60,
      form: {
        phone: '',
        vcode: '',
        inviteCode: '',
      },
      rules: {
        phone: [
          {
            type: 'string',
            required: true,
            message: '请输入手机号',
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
          },
        ],
        vcode: {
          required: true,
          message: '请输入短信验证码',
        },
        // inviteCode: {
        //   required: true,
        //   message: '请输入邀请码',
        // },
      },
      //是否开启邀请
      isRegister: {
        styleVO: {
          imagePath1: '',
          imagePath2: '',
          imagePath3: '',
          imagePath4: '',
          styleInfo1: '',
        },
      },
    };
  },
  async created() {
    const { id } = this.$Route.query;
    this.id = id;
    this.isDisabled = id ? true : false;
    this.form.inviteCode = id;
    this._getInviteStatus();
  },
  methods: {
    //获取是否开启邀请（及样式数据）
    async _getInviteStatus() {
      const { code, data } = await getInviteStatus({ pageType: 'register' });
      if (code != 200) return;
      this.isLoading = false;
      //console.log(data);
      this.isRegister = data;
    },
    //返回上一页
    onBack() {
      uni.navigateBack();
    },
    //发送行为验证码日志(密-明)
    async _sendVcodeLog() {
      let params = {
        phone: this.form.phone,
        vcodeType: 'pcode',
      };
      const { code, data } = await sendVcodeLog(params);
      if (code != 200) return;
      //console.log(data);
    },
    //路由跳转
    goTo(url) {
      this.$Router.push({
        name: url,
      });
    },
    //获取文字
    codeChange(text) {
      this.tips = text;
    },
    codeEnd() {
      this.canGetCode = false;
    },
    //获取验证码 => 天御行为验证码
    async getCode() {
      if (this.form.phone == '') {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none',
        });
        return;
      }
      if (!this.$u.test.mobile(this.form.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
        });
        return;
      }
      //#ifdef H5
      this.$Captcha.show();
      uni.$on('gitTicket', (res) => {
        this.getCodeTo(res);
        uni.$off('gitTicket');
      });
      //#endif
      //#ifdef APP-PLUS
      this.isWeb = true;
      //#endif
    },
    //获取验证码
    async getCodeTo(res) {
      //短信接口方法
      //console.log(res);
      if (res.ret != 0) return;
      let params = {
        captchaVO: {
          randstr: res.randstr,
          ticket: res.ticket,
        },
        phone: this.form.phone,
        smsType: 'register',
      };
      const { code, data } = await sendCode(params);
      if (code != 200) return;
      this.seconds = data;
      this._sendVcodeLog();
      if (this.$refs.uCode.canGetCode) {
        uni.showLoading({
          title: '正在获取验证码',
        });
        setTimeout(() => {
          uni.hideLoading();
          uni.$u.toast('验证码已发送');
          this.canGetCode = this.$refs.uCode.canGetCode;
          this.$refs.uCode.start();
        }, 1000);
      } else {
        uni.$u.toast('倒计时结束后再发送');
      }
    },
    //注册
    async onRegister() {
      try {
        // 处理邀请码是否必填  => 邀请码是否为空 0-可为空 1-必填
        if (this.isRegister.isBuyerNoempty == 1) {
          if (!this.form.inviteCode) {
            uni.showToast({
              title: '邀请码不能为空',
              icon: 'none',
            });
            return;
          }
        }
        await this.$refs.form.validate();
        let params = {
          vcode: this.form.vcode,
          inviteCode: this.form.inviteCode,
          phone: this.form.phone,
        };
        const { code, data } = await register(params);
        if (code != 200) return;
        const { accessToken, expireTime } = data;
        // console.log(accessToken);
        // console.log(expireTime);
        uni.setStorageSync(
          'tokenBuy' + process.env.VUE_APP_PLATFORMID,
          accessToken
        );
        uni.setStorageSync('expireAtBuy', expireTime * 1000);
        await this.$store.dispatch('getUser');
        // 注册成功直接登录跳转首页
        uni.$u.toast('恭喜您！注册成功');
        setTimeout(() => {
          this.$Router.replaceAll({
            name: 'index',
          });
        }, 1000);
      } catch (error) {
        console.error(error);
      }
    },
    //html/index页面发来的消息
    handleMessage(e) {
      uni.setNavigationBarTitle({
        title: '注册',
      });
      let data = e.detail.data[0];
      if (data.ret === 2) {
        this.isWeb = false;
      }
      if (data.ret === 0) {
        this.getCodeTo(data);
        this.isWeb = false;
      }
    },
  },
};
</script>

<style></style>
